package com.example.ktdemo.selection;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * FileName: SelectionBaseView
 * Author: lzt
 * Date: 2022/10/9 18:04
 */
public abstract class SelectionBaseView extends View {
    private final ConcurrentHashMap<String, ValueAnimator> animMap = new ConcurrentHashMap<>();

    public SelectionBaseView(Context context) {
        super(context);
    }

    public SelectionBaseView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SelectionBaseView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void stopAnimAndRemoveCallbacks() {
        for (Map.Entry<String, ValueAnimator> entry : animMap.entrySet()) {
            entry.getValue().cancel();
        }
        animMap.clear();
    }

    protected void startValueAnimator(String tag, ValueAnimator valueAnimator) {
        ValueAnimator oldValueAnimator = animMap.get(tag);
        if (oldValueAnimator != null) {
            oldValueAnimator.cancel();
            animMap.remove(tag);
        }
        animMap.put(tag, valueAnimator);
        valueAnimator.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        stopAnimAndRemoveCallbacks();
        super.onDetachedFromWindow();
    }

    protected ValueAnimator getValueAnimator(String tag) {
        return animMap.get(tag);
    }

    protected int dp2px(int dpValue) {
        return (int) getContext().getResources().getDisplayMetrics().density * dpValue;
    }

    protected Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        try {
            Bitmap resultBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            return resultBitmap;
        } catch (OutOfMemoryError ex) {
        }
        return null;
    }



}
